<?php

namespace app\models;

use think\Model;

class Agent extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $updateTime = 'updated';


    /**
     * 资产变动变更记录
     * $type = 1订单  2提现 3提现驳回
     * @return void
     */
    public static function MoneyEdit($agentid, $type = 0, $money = 0, $info = '', $source = 0, $comeuser_id = 0)
    {
        if ($money != 0) {
            $agent = (new Agent())->where('id', $agentid)->find();
            if (!empty($agent)) {
                if ($money < 0 && $agent['money'] < abs($money)) {
                    throw new \Exception("余额不足", 100);
                }
                $res = (new Agent())->where(['id' => $agent['id'], 'money' => $agent['money']])->setInc('money', $money);
                $res2 = (new AgentLog())->save([
                    'timeid' => floor(microtime(true) * 1000),
                    'types' => 1,
                    'user_id' => $agent['id'],
                    'comeuser_id' => $comeuser_id,
                    'befores' => $agent['money'],
                    'money' => $money,
                    'after' => ($agent['money'] + $money),
                    'type' => $type,
                    'info' => $info,
                    'source' => $source
                ]);
                if (!$res || !$res2) {
                    throw new \Exception("资产记录失败，请重试", 100);
                }
            }
        }
    }

    /**
     * 资产变动变更记录
     * $type = 1订单  2提现 3提现驳回
     * @return void
     */
    public static function MoneyEdit2($agentid, $type = 0, $money = 0, $info = '', $source = 0, $comeuser_id = 0)
    {
        if ($money != 0) {
            $agent = (new Agent())->where('id', $agentid)->find();
            if (!empty($agent)) {
                if ($money < 0 && $agent['money2'] < abs($money)) {
                    //throw new \Exception("余额不足", 100);
                }
                $res = (new Agent())->where(['id' => $agent['id'], 'money2' => $agent['money2']])->setInc('money2', $money);
                $res2 = (new AgentLog())->save([
                    'timeid' => floor(microtime(true) * 1000),
                    'types' => 2,
                    'user_id' => $agent['id'],
                    'comeuser_id' => $comeuser_id,
                    'befores' => $agent['money2'],
                    'money' => $money,
                    'after' => ($agent['money2'] + $money),
                    'type' => $type,
                    'info' => $info,
                    'source' => $source
                ]);
                if (!$res || !$res2) {
                    throw new \Exception("资产记录失败，请重试", 100);
                }
            }
        }
    }
}
